package com.af.security.auth.login.service;


import com.af.security.auth.user.detail.AuthMenu;
import com.af.security.mgt.permisson.Permission;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : zhenyun.su
 * @since : 2020/6/10
 * @commit: 获取树形结构菜单，将用户所有角色对应permission列表转换为树形结构的菜单
 */

public final class AfMenuService {
    public final Long rootId = 0L;
    private List<AuthMenu> menus;

    public AfMenuService(List<Permission> permissions) {
        this.menus= new ArrayList<>();
        if (!ObjectUtils.isEmpty(permissions)) {
            permissions.forEach(permission -> {
                AuthMenu authMenu = new AuthMenu();
                BeanUtils.copyProperties(permission, authMenu);
                authMenu.setGroup(permission.getHeading());
                menus.add(authMenu);
            });
        }
    }

    /*
     * @comment : 根据pid，获取AuthMenu
     */
    private List<AuthMenu> findChildNodes(List<AuthMenu> sources, Long Pid){
        List<AuthMenu> childNodes= new ArrayList<>();
        for (AuthMenu menu : sources) {
            if (Pid.equals(menu.getPid())){
                childNodes.add(menu);
            }
        }
        return childNodes;
    }

    /*
     * @comment : 通过递归方式，从sources获取child节点放入node
     */
    private void addChildren(List<AuthMenu> sources, AuthMenu node){
        List<AuthMenu> childNodes= findChildNodes(sources, node.getId());
        node.setChildren(childNodes);
        for (AuthMenu childNode : childNodes) {
            addChildren(sources, childNode);
        }
    }

    /*
     * @comment : 通过rootId来获取跟节点
     */
    public List<AuthMenu> getMenuTree(List<AuthMenu> sources, Long rootId){
        List<AuthMenu> rootNodes= findChildNodes(sources,rootId);
        for (AuthMenu rootNode : rootNodes) {
            addChildren(sources, rootNode);
        }
        return rootNodes;
    }

    public List<AuthMenu> getMenuTree(){
        return getMenuTree(menus, this.rootId);
    }
}
